import{ useState, useEffect } from 'react';
import {
  Button, Card, Modal, Tag,
   Typography,  Skeleton, message,
   Form, Checkbox, Table, Space, Row, Col, Tabs
} from 'antd';
import {
  PlusOutlined, CalendarOutlined, SettingOutlined,
  SyncOutlined, SaveOutlined, UserOutlined,
  EditOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';

// 扩展 dayjs 功能
dayjs.locale('zh-cn');

import 'antd/dist/reset.css';
import './Arrange.css'; // 引入自定义样式文件
import { UpdateArrange } from '../../component/arrange/UpdateArrange';
import { AddArrange } from '../../component/arrange/AddArrange';
import { DateDetailsModal } from '../../component/arrange/DateDetailsModal';
import { ConfigModal } from '../../component/arrange/ConfigModal';
import { ChangeArrange } from '../../component/arrange/ChangeArrange';

// 部门列表 - 独立管理部门数据
const departments = [
  '针灸治疗',
  '推拿按摩',
  '拔罐疗法',
  '艾灸养生',
  '康复训练',
  '中医诊断'
];

// 固定数据 - 支持多员工结构
const fixedSchedules = [
  { 
    id: '2025-09-15-morning', 
    date: '2025-09-15', 
    timeSlot: '上午班', 
    timeRange: '09:00-12:00',
    doctors: [
      { id: 1, name: '陈员工', department: '针灸治疗'},
      { id: 2, name: '李员工', department: '推拿按摩'},
      { id: 3, name: '王员工', department: '拔罐疗法'},
      { id: 4, name: '赵员工', department: '艾灸养生'},
    ],
    status: 'scheduled' 
  },
  { 
    id: '2025-09-15-afternoon', 
    date: '2025-09-15', 
    timeSlot: '下午班', 
    timeRange: '14:00-17:00',
    doctors: [
      { id: 5, name: '张员工', department: '针灸治疗'},
      { id: 6, name: '刘员工', department: '推拿按摩'},
      { id: 7, name: '黄员工', department: '拔罐疗法'},
    ],
    status: 'scheduled' 
  },
  { 
    id: '2025-09-15-evening', 
    date: '2025-09-15', 
    timeSlot: '晚班', 
    timeRange: '18:00-21:00',
    doctors: [
      { id: 1, name: '陈员工', department: '针灸治疗'},
      { id: 6, name: '刘员工', department: '推拿按摩'},
    ],
    status: 'scheduled' 
  },
  { 
    id: '2025-09-16-morning', 
    date: '2025-09-16', 
    timeSlot: '上午班', 
    timeRange: '09:00-12:00',
    doctors: [
      { id: 1, name: '陈员工', department: '针灸治疗'},
      { id: 3, name: '王员工', department: '拔罐疗法'},
    ],
    status: 'scheduled' 
  }
];


// 可用员工列表 - 将specialties改为department，每个员工属于一个部门
const availableDoctors = [
  // 针灸治疗部门
  { id: 1, name: '陈员工', department: '针灸治疗', avatar: 'https://picsum.photos/id/64/40/40' },
  { id: 5, name: '张员工', department: '针灸治疗', avatar: 'https://picsum.photos/id/65/40/40' },
  { id: 8, name: '吴员工', department: '针灸治疗', avatar: 'https://picsum.photos/id/66/40/40' },
  { id: 9, name: '郑员工', department: '针灸治疗', avatar: 'https://picsum.photos/id/67/40/40' },
  
  // 推拿按摩部门
  { id: 2, name: '李员工', department: '推拿按摩', avatar: 'https://picsum.photos/id/91/40/40' },
  { id: 6, name: '刘员工', department: '推拿按摩', avatar: 'https://picsum.photos/id/92/40/40' },
  { id: 10, name: '孙员工', department: '推拿按摩', avatar: 'https://picsum.photos/id/93/40/40' },
  { id: 11, name: '周员工', department: '推拿按摩', avatar: 'https://picsum.photos/id/94/40/40' },
  
  // 拔罐疗法部门
  { id: 3, name: '王员工', department: '拔罐疗法', avatar: 'https://picsum.photos/id/22/40/40' },
  { id: 7, name: '黄员工', department: '拔罐疗法', avatar: 'https://picsum.photos/id/23/40/40' },
  { id: 12, name: '徐员工', department: '拔罐疗法', avatar: 'https://picsum.photos/id/24/40/40' },
  
  // 艾灸养生部门
  { id: 4, name: '赵员工', department: '艾灸养生', avatar: 'https://picsum.photos/id/33/40/40' },
  { id: 13, name: '马员工', department: '艾灸养生', avatar: 'https://picsum.photos/id/34/40/40' },
  { id: 14, name: '朱员工', department: '艾灸养生', avatar: 'https://picsum.photos/id/35/40/40' },
  
  // 新增部门员工
  { id: 15, name: '林员工', department: '康复训练', avatar: 'https://picsum.photos/id/44/40/40' },
    { id: 17, name: '好员工', department: '康复训练', avatar: 'https://picsum.photos/id/44/40/40' },
  { id: 16, name: '何员工', department: '中医诊断', avatar: 'https://picsum.photos/id/45/40/40' },
   { id: 17, name: '启员工', department: '中医诊断', avatar: 'https://picsum.photos/id/45/40/40' },
];

// 默认排班配置 - 按部门设置排班规则
export const defaultScheduleConfig = {
  // 每周各天是否启用自动排班
  daysEnabled: [true, true, true, true, true, true, true], // 周一至周日
  
  // 各部门每班需要的员工数量 - 按部门配置
  departmentQuota: {
    '针灸治疗': { morning: 2, afternoon: 2, evening: 1 },
    '推拿按摩': { morning: 2, afternoon: 2, evening: 1 },
    '拔罐疗法': { morning: 1, afternoon: 1, evening: 0 },
    '艾灸养生': { morning: 1, afternoon: 1, evening: 0 },
    '康复训练': { morning: 1, afternoon: 1, evening: 0 },
    '中医诊断': { morning: 1, afternoon: 0, evening: 0 }
  },
  
  // 员工休息日设置 - 为每位员工设置不同的休息日（0-6对应周一到周日）
  doctorRestDays: {
    1: [0],   // 陈员工 周一休息
    2: [1],   // 李员工 周二休息
    3: [2],   // 王员工 周三休息
    4: [3],   // 赵员工 周四休息
    5: [4],   // 张员工 周五休息
    6: [5],   // 刘员工 周六休息
    7: [6],   // 黄员工 周日休息
    8: [0, 3],// 吴员工 周一、周四休息
    9: [1, 4],// 郑员工 周二、周五休息
    10: [2, 5],// 孙员工 周三、周六休息
    11: [6],  // 周员工 周日休息
    12: [0],  // 徐员工 周一休息
    13: [1],  // 马员工 周二休息
    14: [2],  // 朱员工 周三休息
    15: [3],  // 林员工 周四休息
    16: [4]   // 何员工 周五休息
  }
};

export const Arrange = () => {
  // 状态管理
  const [isShow, setIsShow] = useState(true);
  const [currentDate, setCurrentDate] = useState(dayjs());
  const [schedules, setSchedules] = useState(fixedSchedules); // 重命名避免混淆

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentSchedule, setCurrentSchedule] = useState(null);
  
  // 员工休息日设置相关状态
  const [selectedDoctor, setSelectedDoctor] = useState(null);
  const [doctorRestDaysForm] = Form.useForm();
  const [activeTabKey, setActiveTabKey] = useState('scheduleConfig');
  const [isRestDayModalVisible, setIsRestDayModalVisible] = useState(false);

  const [expandedSchedules, setExpandedSchedules] = useState({});
  // 跟踪员工排班次数，用于公平分配
  const [doctorShiftCounts, setDoctorShiftCounts] = useState({});
  // 日期详情模态框相关状态
  const [isDateDetailVisible, setIsDateDetailVisible] = useState(false);
  const [selectedDate, setSelectedDate] = useState(null);
  // 自动排班配置相关状态
  const [isConfigModalVisible, setIsConfigModalVisible] = useState(false);
  const [scheduleConfig, setScheduleConfig] = useState(defaultScheduleConfig);
  const [form] = Form.useForm();

  // 初始化员工排班计数
  useEffect(() => {
    const initialCounts = {};
    availableDoctors.forEach(doctor => {
      initialCounts[doctor.id] = 0;
    });
    setDoctorShiftCounts(initialCounts);
  }, []);

  // 修复：更新员工排班计数 - 移除doctorShiftCounts作为依赖
  useEffect(() => {
    // 从可用员工列表创建全新的计数对象
    const counts = {};
    availableDoctors.forEach(doctor => {
      counts[doctor.id] = 0;
    });
    
    // 计算当前排班中的员工次数
    schedules.forEach(schedule => {
      schedule.doctors.forEach(doctor => {
        if (counts[doctor.id] !== undefined) {
          counts[doctor.id]++;
        }
      });
    });
    
    // 只有当计数发生变化时才更新状态
    let countsChanged = false;
    Object.keys(counts).forEach(id => {
      if (counts[id] !== doctorShiftCounts[id]) {
        countsChanged = true;
      }
    });
    
    if (countsChanged) {
      setDoctorShiftCounts(counts);
    }
  }, [schedules]); // 只依赖schedules

  // 骨架屏控制
  useEffect(() => {
    const timer = setTimeout(() => {
      setIsShow(false);
    }, 2000);
    return () => clearTimeout(timer);
  }, []);

  // 初始化表单
  useEffect(() => {
    form.setFieldsValue(scheduleConfig);
  }, [scheduleConfig, form]);

  // 切换排班展开/折叠状态
  const toggleScheduleExpand = (scheduleId, e) => {
    e.stopPropagation();
    setExpandedSchedules(prev => ({
      ...prev,
      [scheduleId]: !prev[scheduleId]
    }));
  };

  const changeWeek = (direction) => {
    setCurrentDate(prev =>
      direction === 'prev' ? prev.subtract(1, 'week') : prev.add(1, 'week')
    );
  };

  // 打开排班模态框
  const openScheduleModal = (schedule = null) => {
    const now = dayjs();
    let timeSlot, timeRange;
    
    // 根据当前时间自动选择合适的班次
    if (now.hour() < 12) {
      timeSlot = '上午班';
      timeRange = '09:00-12:00';
    } else if (now.hour() < 17) {
      timeSlot = '下午班';
      timeRange = '14:00-17:00';
    } else {
      timeSlot = '晚班';
      timeRange = '18:00-21:00';
    }
    
    const initialData = schedule || {
      id: `${now.format('YYYY-MM-DD')}-${timeSlot}-${Date.now()}`,
      date: now.format('YYYY-MM-DD'),
      timeSlot,
      timeRange,
      doctors: [],
      status: 'available'
    };
    setCurrentSchedule(initialData);
    
    setIsModalVisible(true);
  };

  // 打开日期详情模态框
  const openDateDetailModal = (date, e) => {
    e.stopPropagation();
    setSelectedDate(date);
    setIsDateDetailVisible(true);
  };

  // 关闭模态框
  const handleCancel = () => {
    setIsModalVisible(false);
    setCurrentSchedule(null);

    setIsDateDetailVisible(false);
    setSelectedDate(null);
    setIsConfigModalVisible(false);
      
    
    setSelectedDoctor(null);
  };

  const handleCancelRestDay=()=>{
    setIsRestDayModalVisible(false);
  }

  // 获取选定日期的所有排班
  const getSelectedDateSchedules = () => {
    if (!selectedDate) return [];
    const dateStr = selectedDate.format('YYYY-MM-DD');
    return schedules
      .filter(schedule => schedule.date === dateStr)
      .sort((a, b) => {
        // 排序：上午班 > 下午班 > 晚班
        const slotOrder = { '上午班': 1, '下午班': 2, '晚班': 3 };
        return slotOrder[a.timeSlot] - slotOrder[b.timeSlot];
      });
  };

  const addDoctorToSchedule = (doctor) => {
    if (!currentSchedule) return;
    
    // 检查该员工在当前排班日期是否休息
    const scheduleDate = dayjs(currentSchedule.date);
    const dayOfWeek = scheduleDate.day() || 7; // 转换为周一为1，周日为7
    const dayIndex = dayOfWeek - 1; // 转换为0-6的索引
    
    const doctorRestDays = scheduleConfig.doctorRestDays[doctor.id] || [];
    if (doctorRestDays.includes(dayIndex)) {
      message.warning(`${doctor.name}在${['周一', '周二', '周三', '周四', '周五', '周六', '周日'][dayIndex]}休息，不能排班`);
      return;
    }
    
    const doctorExists = currentSchedule.doctors.some(d => d.name === doctor.name);
    if (doctorExists) {
      message.warning(`${doctor.name}已在该班次值班`);
      return;
    }
    
    // 检查该部门在当前班次是否已达上限
    const slotKey = currentSchedule.timeSlot === '上午班' ? 'morning' : 
                  currentSchedule.timeSlot === '下午班' ? 'afternoon' : 'evening';
                  
    const departmentQuota = scheduleConfig.departmentQuota[doctor.department]?.[slotKey] || 0;
    const departmentCount = currentSchedule.doctors.filter(d => d.department === doctor.department).length;
    
    if (departmentCount >= departmentQuota && departmentQuota > 0) {
      message.warning(`${doctor.department}在${currentSchedule.timeSlot}已达最大配置人数(${departmentQuota}人)`);
      return;
    }
    
    const updatedDoctors = [
      ...currentSchedule.doctors,
      {
        id: Date.now(),
        name: doctor.name,
        department: doctor.department,
      }
    ];
    
    const updatedSchedule = {
      ...currentSchedule,
      doctors: updatedDoctors,
      status: updatedDoctors.length > 0 ? 'scheduled' : 'available'
    };
    
    setCurrentSchedule(updatedSchedule);
  };

  const removeDoctorFromSchedule = (doctorId) => {
    if (!currentSchedule) return;
    
    const updatedDoctors = currentSchedule.doctors.filter(d => d.id !== doctorId);
    const updatedSchedule = {
      ...currentSchedule,
      doctors: updatedDoctors,
      status: updatedDoctors.length > 0 ? 'scheduled' : 'available'
    };
    
    setCurrentSchedule(updatedSchedule);
  };

  const handleSaveSchedule = () => {
    if (!currentSchedule) return;
    
    message.success('排班已保存');
    setIsModalVisible(false);
    
    if (schedules.some(s => s.id === currentSchedule.id)) {
      const updatedSchedules = schedules.map(item =>
        item.id === currentSchedule.id ? currentSchedule : item
      );
      setSchedules(updatedSchedules);
    } else {
      setSchedules([...schedules, currentSchedule]);
    }
    
    setCurrentSchedule(null);
  };

  // 打开员工休息日设置（在排班设置模态框内）
  const openRestDaySetting = (doctor) => {
    //选择设置休息日的员工信息
    //console.log(doctor)
    setSelectedDoctor(doctor);
    setIsRestDayModalVisible(true);
    // 切换到休息日设置标签
    setActiveTabKey('restDays');
    
    // 初始化表单数据
    const restDays = scheduleConfig.doctorRestDays[doctor.id] || [];
    doctorRestDaysForm.setFieldsValue({
      restDays: restDays
    });
  };

  // 保存员工休息日设置
  const saveDoctorRestDays = async () => {
    if (!selectedDoctor) return;
    
    try {
      const values = await doctorRestDaysForm.validateFields();
      
      // 更新排班配置中的员工休息日
      const updatedRestDays = {
        ...scheduleConfig.doctorRestDays,
        [selectedDoctor.id]: values.restDays
      };
      
      const updatedConfig = {
        ...scheduleConfig,
        doctorRestDays: updatedRestDays
      };
      
      setScheduleConfig(updatedConfig);
      setIsRestDayModalVisible(false);
      message.success(`${selectedDoctor.name}的休息日已更新`);
    } catch (info) {
      console.log('Validate Failed:', info);
    }
  };

  const getCurrentWeekDates = () => {
    const start = currentDate.startOf('week');
    const dates = Array.from({ length: 7 }, (_, i) => start.add(i, 'day'));
    return dates;
  };

  // 定义班次：上午班、休息时间、下午班、休息时间和晚班
  const getTimeSlots = () => [
    { slot: '上午班', range: '09:00-12:00', type: 'work' },
    { slot: '午休时间', range: '12:00-14:00', type: 'rest' },
    { slot: '下午班', range: '14:00-17:00', type: 'work' },
    { slot: '傍晚休息', range: '17:00-18:00', type: 'rest' },
    { slot: '晚班', range: '18:00-21:00', type: 'work' }
  ];

  // 保存排班配置（包括所有标签页的设置）
  const handleSaveConfig = async () => {
    try {
      // 保存排班配置表单
      const configValues = await form.validateFields();
      
      // 保留原有的员工休息日配置
      const updatedDoctorRestDays = { ...scheduleConfig.doctorRestDays };
      
      // 如果正在编辑员工休息日，更新该员工的休息日
      if (selectedDoctor) {
        const restDayValues = await doctorRestDaysForm.validateFields();
        updatedDoctorRestDays[selectedDoctor.id] = restDayValues.restDays;
      }
      
      // 合并配置，确保保留所有员工的休息日设置
      const updatedConfig = {
        ...configValues,
        doctorRestDays: updatedDoctorRestDays
      };
      
      setScheduleConfig(updatedConfig);
      message.success('所有排班设置已保存');
      setIsConfigModalVisible(false);
    } catch (info) {
      console.log('Validate Failed:', info);
    }
  };

  // 根据配置生成未来一周的排班，实现公平分配并考虑员工休息日
  const generateWeeklySchedule = () => {
    // 复制当前排班计数用于临时计算
    let tempCounts = { ...doctorShiftCounts };
    const newSchedules = [];
    const today = dayjs();
    
    // 生成未来7天的排班
    for (let dayOffset = 0; dayOffset < 7; dayOffset++) {
      const currentDay = today.add(dayOffset, 'day');
      const dayOfWeek = currentDay.day() || 7; // 转换为周一为1，周日为7
      const dayIndex = dayOfWeek - 1; // 转换为0-6的索引
      
      // 检查该天是否启用自动排班
      if (!scheduleConfig.daysEnabled[dayIndex]) {
        continue;
      }
      
      const dateStr = currentDay.format('YYYY-MM-DD');
      const timeSlots = getTimeSlots().filter(slot => slot.type === 'work'); // 只生成工作班次
      
      // 为每个时段生成排班
      timeSlots.forEach(({ slot, range }) => {
        // 检查是否已有该时段的排班
        const existingScheduleIndex = schedules.findIndex(
          s => s.date === dateStr && s.timeSlot === slot
        );
        
        // 如果已有排班则跳过或更新
        if (existingScheduleIndex >= 0) {
          // 更新临时计数以反映现有排班
          schedules[existingScheduleIndex].doctors.forEach(doctor => {
            if (tempCounts[doctor.id] !== undefined) {
              tempCounts[doctor.id]++;
            }
          });
          return;
        }
        
        // 根据配置生成员工排班
        const doctors = [];
        
        // 转换班次名称为配置中的键名
        const slotKey = slot === '上午班' ? 'morning' : 
                       slot === '下午班' ? 'afternoon' : 'evening';
        
        // 按部门分配员工
        departments.forEach(department => {
          const quota = scheduleConfig.departmentQuota[department]?.[slotKey] || 0;
          if (quota <= 0) return;
          
          // 查找该部门且当天不休息的员工
          let departmentDoctors = availableDoctors.filter(doctor => {
            const doctorRestDays = scheduleConfig.doctorRestDays[doctor.id] || [];
            return doctor.department === department && 
                   !doctorRestDays.includes(dayIndex); // 排除休息日的员工
          });
          
          // 按排班次数排序，优先选择排班次数少的员工（公平分配）
          departmentDoctors = [...departmentDoctors].sort((a, b) => {
            const countA = tempCounts[a.id] || 0;
            const countB = tempCounts[b.id] || 0;
            return countA - countB;
          });
          
          // 检查是否有足够的可用员工
          if (departmentDoctors.length < quota) {
            message.warning(`在${currentDay.format('MM-DD')}${slot}，${department}部门可用员工不足`);
          }
          
          // 分配指定数量的员工
          for (let i = 0; i < quota && i < departmentDoctors.length; i++) {
            const doctor = departmentDoctors[i];
            
            // 更新临时计数
            tempCounts[doctor.id] = (tempCounts[doctor.id] || 0) + 1;
            
            doctors.push({
              id: doctor.id,
              name: doctor.name,
              department: doctor.department,
              avatar: doctor.avatar
            });
          }
        });
        
        // 创建新排班
        newSchedules.push({
          id: `${dateStr}-${slot}-${Date.now()}`,
          date: dateStr,
          timeSlot: slot,
          timeRange: range,
          doctors,
          status: doctors.length > 0 ? 'scheduled' : 'available'
        });
      });
    }
    
    // 添加新生成的排班
    setSchedules([...schedules, ...newSchedules]);
    //生成的本周排班信息
    //console.log(newSchedules,';;;')
    message.success(`已生成 ${newSchedules.length} 个新排班`);
  };

  // 员工休息日表格的列定义 - 显示部门信息
  const doctorRestDaysColumns = [
    {
      title: '员工姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <img 
            src={record.avatar} 
            alt={text} 
            style={{ width: 30, height: 30, borderRadius: '50%', marginRight: 8 }} 
          />
          {text}
        </div>
      )
    },
    {
      title: '所属部门',
      dataIndex: 'department',
      key: 'department',
     
    },
    {
      title: '休息日',
      key: 'restDays',
      render: (_, record) => {
        const restDays = scheduleConfig.doctorRestDays[record.id] || [];
        const dayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        return (
          <Space>
            {restDays.map(day => (
              <Tag key={day} color="orange">{dayNames[day]}</Tag>
            ))}
            {restDays.length === 0 && <Tag color="gray">无</Tag>}
          </Space>
        );
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button 
          type="text" 
          icon={<EditOutlined />} 
          onClick={() => openRestDaySetting(record)}
        >
          设置休息日
        </Button>
      )
    }
  ];

  // 辅助函数：为不同部门提供不同颜色
  const getDepartmentColor = (department) => {
    const colorMap = {
      '针灸治疗': 'blue',
      '推拿按摩': 'green',
      '拔罐疗法': 'purple',
      '艾灸养生': 'orange',
      '康复训练': 'red',
      '中医诊断': 'geekblue'
    };
    return colorMap[department] || 'default';
  };

  const renderScheduleCell = (date, timeSlot) => {
    // 休息时段特殊处理
    if (timeSlot.type === 'rest') {
      return (
        <div 
          style={{ 
            height: "30px", 
            backgroundColor: "#dededeff", 
            display: "flex", 
            alignItems: "center", 
            justifyContent: "center",
            border: "1px solid #e0e0e0",
            borderRadius: "4px",
            color:"gray"
          }}
          className="rest-slot"
        >
          <div style={{ textAlign: "center" }}>
            <div className="font-medium text-gray-600">{timeSlot.slot}</div>
          </div>
        </div>
      );
    }

    // 工作时段正常渲染
    const dateStr = date.format('YYYY-MM-DD');
    const schedule = schedules.find(s => s.date === dateStr && s.timeSlot === timeSlot.slot);
    const isExpanded = expandedSchedules[schedule?.id] || false;
    const maxVisible = 3;

    if (!schedule || schedule.status === 'available' || schedule.doctors.length === 0) {
      return (
        <div
          style={{height:"90px"}}
          className="available-slot border border-green-200 hover:shadow-md cursor-pointer h-full p-2 transition-all duration-200"
          onClick={() => openScheduleModal(schedule)}
        >
          <div className="font-medium">{timeSlot.slot}</div>
          <div className="text-sm text-gray-500 mb-2">{timeSlot.range}</div>
          <div style={{ color: "gray", marginTop: 4 }}>点击安排员工</div>
        </div>
      );
    }

    return (
      <div
        className="scheduled-slot border border-yellow-200 hover:shadow-md cursor-pointer h-full p-2 transition-all duration-200"
        onClick={() => openScheduleModal(schedule)}
      >
        <div style={{position:"relative"}} className="flex justify-between items-center mb-2 pb-1 border-b border-gray-100">
         
         <label style={{position:"absolute",right:14,color:"#888888ff",backgroundColor:"#ddd",fontSize:"10px",padding:2,borderRadius:4}}> {schedule.doctors.length}位员工</label>
        </div>
        
        <div style={{height:"80px",overflowY:"auto"}}>
          {schedule.doctors.slice(0, isExpanded ? schedule.doctors.length : maxVisible).map((doctor, index) => (
            <div 
              key={`${doctor.id}-${index}`}
              className="p-1.5 bg-gray-50 rounded border border-gray-100 flex justify-between items-center hover:bg-gray-100 transition-colors"
            >
              <div className="flex-1 min-w-0">
                <div className="font-medium text-sm truncate">{doctor.name}</div>
                <div style={{ color: "gray", fontSize: "0.75rem" }} className="truncate">
                  
                    {doctor.department}
               
                </div>
              </div>
            </div>
          ))}
          
          {!isExpanded && schedule.doctors.length > maxVisible && (
            <div 
             style={{fontSize:"10px",marginTop:6}}
              onClick={(e) => toggleScheduleExpand(schedule.id, e)}
            >
              还有 {schedule.doctors.length - maxVisible} 位员工... 点击展开
            </div>
          )}
        </div>
      </div>
    );
  };

  const weekDates = getCurrentWeekDates();
  const timeSlots = getTimeSlots();
  const dateSchedules = getSelectedDateSchedules();

  return (
    <div>
      {isShow ? (
        <Skeleton paragraph={{ rows: 10 }} active />
      ) : (
        <div style={{width:"100%"}} className="mx-auto p-4 md:p-6 max-w-7xl bg-gray-50 min-h-screen">
          {/* 页面标题和操作区 */}
          <div className="mb-6">
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 10 }}>
              <div>
                <Typography.Title level={2} className="text-secondary mb-1">排班管理</Typography.Title>
                <Typography.Text type="secondary">按部门管理员工排班和预约时段</Typography.Text>
              </div>
              <div style={{ marginTop: 10, display: 'flex', gap: 10 }}>
                <Button
                  type="primary"
                  icon={<SyncOutlined />}
                  onClick={generateWeeklySchedule}
                >
                  生成一周排班
                </Button>
                <Button
                  type="default"
                  icon={<SettingOutlined />}
                  onClick={() => setIsConfigModalVisible(true)}
                >
                  排班设置
                </Button>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => openScheduleModal()}
                >
                  新增排班
                </Button>
              </div>
            </div>
          </div>

          {/* 周排班表 */}
          <Card className="shadow-md mb-6 overflow-hidden">
            <div style={{ display: "flex", justifyContent: "space-between", padding: "0 16px" }}>
              <Typography.Title level={5} className="text-secondary m-0">本周排班表</Typography.Title>
              <div style={{ display: "flex", gap: 10, marginBottom: 10 }}>
                {/* <Button onClick={() => changeWeek('prev')}>上一周</Button> */}
                <Button onClick={() => changeWeek('next')}>下一周</Button>
                <Button onClick={() => setCurrentDate(dayjs())} className="border">本周</Button>
              </div>
            </div>

            <div style={{ padding: '0 16px 16px' }}>
              <table className="schedule-table" style={{ width: '100%', tableLayout: 'fixed' }}>
                <thead>
                  <tr>
                    <th className="time-slot-header">班次/日期</th>
                    {weekDates.map((date, i) => {
                      const isToday = date.isSame(dayjs(), 'day');
                      return (
                        <th 
                          key={`date-${i}-${date.format('YYYY-MM-DD')}`} 
                          className={`date-header ${isToday ? 'today-header' : ''} cursor-pointer hover:bg-blue-50`}
                          style={{ width: `${100/7}%` }}
                          onClick={(e) => openDateDetailModal(date, e)}
                        >
                          <div className="weekday">{['周一', '周二', '周三', '周四', '周五', '周六', '周日'][i]}</div>
                          <div className="date">{date.format('MM/DD')}{isToday && <span className="today-tag"> 今天</span>}</div>
                        </th>
                      );
                    })}
                  </tr>
                </thead>
                <tbody>
                  {timeSlots.map((timeSlot, index) => (
                    <tr key={`timeslot-${index}`} className={timeSlot.type === 'rest' ? 'rest-row' : ''}>
                      <td className={`time-slot-cell ${timeSlot.type === 'rest' ? 'rest-time-header' : ''}`}>
                      
                        <div className="text-sm text-gray-500">{timeSlot.range}</div>
                      </td>
                      {weekDates.map((date, i) => (
                        <td key={`${date.format('YYYY-MM-DD')}-${timeSlot.slot}-${i}`} className="schedule-cell">
                          {renderScheduleCell(date, timeSlot)}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>

          {/* 调班申请 */}
          <ChangeArrange></ChangeArrange>


          {/* 排班编辑模态框 */}
          <Modal
           style={{top:"50px"}}
            open={isModalVisible}
            onCancel={handleCancel}
            footer={false}
            width={"900px"}
          >
            {currentSchedule?.doctors?.length>0?(
              <UpdateArrange 
                data={currentSchedule} 
                onSave={handleSaveSchedule}
                onCancel={handleCancel}
                availableDoctors={availableDoctors}
                addDoctor={addDoctorToSchedule}
                removeDoctor={removeDoctorFromSchedule}
              ></UpdateArrange>
            ):(
              <AddArrange 
              
              ></AddArrange>
            )}
          </Modal>

          {/* 日期详情模态框 */}
          <Modal
            title={
              selectedDate ? (
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <CalendarOutlined style={{ marginRight: '8px', color: '#1890FF' }} />
                  <span>{selectedDate.format('YYYY年MM月DD日')} 排班详情</span>
                  {selectedDate.isSame(dayjs(), 'day') && <Tag color="blue" style={{ marginLeft: '8px' }}>今天</Tag>}
                </div>
              ) : '日期排班详情'
            }
            open={isDateDetailVisible}
            onCancel={handleCancel}
            footer={[
              <Button key="close" onClick={handleCancel}>关闭</Button>
            ]}
            width={700}
            destroyOnHidden={true}
          >
            {dateSchedules.length > 0 ? (
             <DateDetailsModal data={dateSchedules}></DateDetailsModal>
            ) : (
              <div className="no-schedules text-center py-8">
                <Typography.Text type="secondary" style={{ fontSize: 16 }}>
                  该日期暂无任何排班安排
                </Typography.Text>
                {/* 显示休息时间信息 */}
                <div className="rest-reminder mt-4 p-2 bg-gray-50 border border-gray-200 rounded-lg inline-block">
                  <Typography.Text type="secondary" style={{ fontSize: 14 }}>
                    休息时间：中午 12:00-14:00 | 傍晚 17:00-18:00
                  </Typography.Text>
                </div>
                <div style={{ marginTop: 16 }}>
                  <Button 
                    type="primary" 
                    onClick={() => {
                      const now = dayjs();
                      let timeSlot, timeRange;
                      
                      if (now.hour() < 12) {
                        timeSlot = '上午班';
                        timeRange = '09:00-12:00';
                      } else if (now.hour() < 17) {
                        timeSlot = '下午班';
                        timeRange = '14:00-17:00';
                      } else {
                        timeSlot = '晚班';
                        timeRange = '18:00-21:00';
                      }
                      
                      const newSchedule = {
                        id: `${selectedDate.format('YYYY-MM-DD')}-${timeSlot}-${Date.now()}`,
                        date: selectedDate.format('YYYY-MM-DD'),
                        timeSlot,
                        timeRange,
                        doctors: [],
                        status: 'available'
                      };
                      openScheduleModal(newSchedule);
                      setIsDateDetailVisible(false);
                    }}
                  >
                    新增排班
                  </Button>
                </div>
              </div>
            )}
          </Modal>

          {/* 排班配置模态框 - 包含多个标签页 */}
          <Modal
            title="自动排班配置"
            open={isConfigModalVisible}
            onCancel={handleCancel}
            style={{top:15}}
            footer={[
              <Button key="cancel" onClick={handleCancel}>取消</Button>,
              <Button key="save" type="primary" icon={<SaveOutlined />} onClick={handleSaveConfig}>
                保存配置
              </Button>
            ]}
            width={900}
          >
            <Tabs 
              activeKey={activeTabKey} 
              onChange={setActiveTabKey}
            >
              <Tabs.TabPane tab="排班规则设置" key="scheduleConfig">
                <ConfigModal form={form} departments={departments} />
              </Tabs.TabPane>
              
              <Tabs.TabPane tab="员工休息日设置" key="restDays">
             <div className="modal-box">
                 <Card className="mt-4">
                  <Typography.Title level={5} className="text-secondary m-0 mb-4">员工休息日管理</Typography.Title>
                  <Table
                    dataSource={availableDoctors}
                    columns={doctorRestDaysColumns}
                    rowKey="id"
                    pagination={{ pageSize: 5 }}
                  />
                  
                   <Modal
            title={selectedDoctor ? `${selectedDoctor.name}的休息日设置` : "员工休息日设置"}
            open={isRestDayModalVisible}
            onCancel={handleCancelRestDay}
            footer={[
              <Button key="save2" type="primary" onClick={saveDoctorRestDays}>
                保存设置
              </Button>
            ]}
            width={500}
          >
            {selectedDoctor && (
              <Form form={doctorRestDaysForm} layout="vertical">
                <Form.Item 
                  name="restDays" 
                  label="选择休息日"
                  rules={[{ required: true, message: '请至少选择一天作为休息日' }]}
                >
                  <Checkbox.Group>
                    <Row gutter={[8, 8]}>
                      <Col span={12}>
                        <Checkbox value={0}>周一</Checkbox>
                      </Col>
                      <Col span={12}>
                        <Checkbox value={1}>周二</Checkbox>
                      </Col>
                      <Col span={12}>
                        <Checkbox value={2}>周三</Checkbox>
                      </Col>
                      <Col span={12}>
                        <Checkbox value={3}>周四</Checkbox>
                      </Col>
                      <Col span={12}>
                        <Checkbox value={4}>周五</Checkbox>
                      </Col>
                      <Col span={12}>
                        <Checkbox value={5}>周六</Checkbox>
                      </Col>
                      <Col span={12}>
                        <Checkbox value={6}>周日</Checkbox>
                      </Col>
                    </Row>
                  </Checkbox.Group>
                </Form.Item>
              </Form>
            )}
          </Modal>
                </Card>
             </div>
              </Tabs.TabPane>
            </Tabs>
          </Modal>
        </div>
      )}
    </div>
  );
};
